import React from 'react';
import { Link } from 'react-router-dom';
import moment from 'moment';

const getUrlSearch = (name: string) => {
  // 未传参，返回空
  if (!name) return null;
  // 查询参数：先通过search取值，如果取不到就通过hash来取
  let after = window.location.search;
  after = after.substr(1) || window.location.hash.split('?')[1];
  // 地址栏URL没有查询参数，返回空
  if (!after) return null;
  // 如果查询参数中没有"name"，返回空
  if (!after.includes(name)) return null;

  const reg = new RegExp(`(^|&)${name}=([^&]*)(&|$)`);
  // 当地址栏参数存在中文时，需要解码，不然会乱码
  // eslint-disable-next-line @typescript-eslint/prefer-regexp-exec
  const r = decodeURI(after).match(reg);
  // 如果url中"name"没有值，返回空
  if (!r) return null;

  return r[2];
};

let orgId: any = null;

// 获取页面orgId
const getOrgId = (param: any) => {
  orgId = param;
};

// 处理权限
const handleAuth = (configValue: any) => {
  if (configValue === '1') {
    return (
      <span className="text-blue-500">Not open</span>
    );
  }
  if (configValue === '2') {
    return (
      // eslint-disable-next-line @typescript-eslint/restrict-template-expressions
      <Link to={ orgId ? `/institution/edit?id=${orgId}` : '/institution/add'}>
        <span className="mr-2 text-red-600" key={1}>
          Unauthorized
        </span>
        <span className="text-blue-500" key={2}>
            Please login
        </span>
      </Link>
    );
  }

  return ''; // not all code paths return a value
};

let currentId = 0;

const getId = () => {
  currentId += 1;

  return currentId.toString();
};

// 处理数据格式
const toFormat = (info: any, callBack: any) => {
  const _info = { ...info };
  const configValue = _info.data;
  // 权限处理
  if (configValue === '1' || configValue === '2') {
    _info.data = handleAuth(configValue);
    return _info;
  }

  if (_info.isAuthMutiFile) { // 带权限-多文件处理
    _info.data = configValue?.map((url: any) => <div className="mb-1" key={`mutiDiv${getId()}`}><a onClick={() => {
      callBack(url.fileUrl);
    }} key={`mutiA${getId()}`} className="text-blue-500">{url.fileUrl}</a><br key={`mutiBr${getId()}`}/></div>);
  } else if (_info.isAuthSingleFile) { // 带权限-单文件处理 '' /'..' /'1' /'2'
    _info.data = <a onClick={() => {
      callBack(configValue);
    }} className="text-blue-500">{configValue}</a>;
  } else if (_info.isAuthTime) { // 带权限-时间格式处理 null/number/'1'/'2'
    _info.data = configValue ? moment(configValue).format('YYYY/MM/DD') : '';
  } else if (_info.isAuthText) { // 带权限-文本格式处理 '' /'..' /'1' /'2'
    _info.data = configValue;
  } else if (_info.value === 'governmentApprovesStatus') {
    _info.data = configValue ? 'yes' : 'no';
  }
  return _info;
};

// 阶段1数据处理
const identification: Array<any> = [
  {
    title: 'Project Key Information',
    data: [{ key: 'Planned total project investment', value: 'plannedTotalInvestment', isAuthText: true },
      { key: 'Total land area of the project', value: 'totalLandArea', isAuthText: true },
      { key: 'Total length of the project', value: 'totalLength', isAuthText: true },
      { key: 'Project Contract Term', value: 'projectContractTerm', isAuthText: true },
      { key: 'Planned project construction start date', value: 'plannedStartDate', isAuthTime: true },
      { key: 'Planned project construction completion date', value: 'plannedCompletionDate', isAuthTime: true },
      { key: 'Planned Project operation start date', value: 'plannedOperationStartDate', isAuthTime: true },
      { key: 'Planned procurement date', value: 'plannedProcurementDate', isAuthTime: true },
      { key: 'PPP Contract mode', value: 'contractMode', isAuthText: true },
      { key: 'PPP scope of contract', value: 'contractScope', isAuthText: true },
      { key: 'Procurement method of private enterprise', value: 'priProcurementMode', isAuthText: true }],
  },
  {
    title: 'Technical Assessment',
    data: [{ key: 'Project scope outline', value: 'scopeOutline', isAuthText: true },
      { key: 'FSR approval date', value: 'fsrApprovalDate', isAuthTime: true },
      { key: 'Feasibility study report (FSR)', value: 'fsr', isAuthSingleFile: true },
      { key: 'EIA approval date', value: 'eiaApprovalDate', isAuthTime: true },
      { key: 'Environment Impact Assessment report (EIA)', value: 'eia', isAuthSingleFile: true },
      { key: 'Output description of the project', value: 'outputDescription', isAuthText: true }],
  },
  {
    title: 'Financial Assessment',
    data: [
      { key: 'Value-for-money evaluation (VFM)', value: 'vfm', isAuthMutiFile: true },
      { key: 'Fiscal affordability assessment(FAA)', value: 'faa', isAuthMutiFile: true },
      { key: 'Planned private sector investment amount', value: 'plannedPriInvestmentAmount', isAuthText: true },
      {
        key: 'Planned government investment and expenditures that need to be arranged from the budget',
        value: 'plannedGovernmentSpending',
        isAuthText: true,
      },
      { key: 'International financial support', value: 'internationalFinancialSupport', isAuthText: true },
      { key: 'Planned financing structure', value: 'plannedFinancingStructure', isAuthText: true },
      { key: 'Return mechanism', value: 'returnMechanism', isAuthText: true }],
  },
  {
    title: 'Implementation Strategy',
    data: [
      { key: 'Risk allocation framework', value: 'riskAllocationFramework', isAuthSingleFile: true },
      { key: 'The core content of the PPP project contract', value: 'contractCoreContent', isAuthSingleFile: true },
      { key: 'Contract system', value: 'contractSystem', isAuthSingleFile: true },
      { key: 'Performance evaluation indicators and system', value: 'indicatorsAndSystem', isAuthSingleFile: true },
      { key: 'PPP-related regulatory framework', value: 'regulatoryFramework', isAuthSingleFile: true },
      { key: 'Tax policy for foreign investors', value: 'foreignInvestorsTaxPolicy', isAuthText: true },
      {
        key: 'Foreign exchange policy for foreign investors',
        value: 'foreignInvestorsExchangePolicy',
        isAuthText: true,
      }],
  },
];

// 阶段2数据处理
const procurement: Array<any> = [
  {
    title: 'Tendering',
    data: [
      { key: 'Pre-qualification announcement', value: 'preQualificationAnnouncement', isAuthSingleFile: true },
      { key: 'Shortlist of pre-qualified bidders', value: 'preQualifiedShortlist', isAuthSingleFile: true },
      { key: 'Request for proposal（RFP）', value: 'rfp', isAuthSingleFile: true },
      { key: 'Tender proposal submission deadline', value: 'tenderSubmissionDeadline', isAuthTime: true },
      { key: 'List of the bidders submitting proposals', value: 'bidderList', isAuthSingleFile: true },
      { key: 'Bids evaluation result', value: 'bidsEvaluationResult', isAuthSingleFile: true },
      { key: 'Final negotiation date', value: 'finalNegotiationDate', isAuthTime: true },
      { key: 'Winning bidder(s)', value: 'winningBidder', isAuthText: true }],
  },
  {
    title: 'Contract Execution',
    data: [
      { key: 'Whether the government approves the PPP contract to be signed', value: 'governmentApprovesStatus' },
      { key: 'Approval date', value: 'approvalDate', isAuthTime: true },
      { key: 'Contract signing date', value: 'contractSigningDate', isAuthTime: true },
      {
        key: 'According to the signed PPP project contract, the agreed investment amount of the project',
        value: 'contractAgreedInvestmentAmount',
        isAuthText: true,
      },
      {
        key: 'the agreed private investment amount of the project',
        value: 'privateAgreedInvestmentAmount',
        isAuthText: true,
      },
      {
        key: 'the agreed government investment and expenditures that need to be arranged from government budge',
        value: 'contractBudgetExpenditure',
        isAuthText: true,
      },
      { key: 'The signed PPP project contract', value: 'theSignedContract', isAuthSingleFile: true },
      { key: 'Core terms of the signed PPP project contract', value: 'contractCoreTerms', isAuthSingleFile: true }],
  },
];

// 阶段3数据处理
const implementation: Array<any> = [
  {
    title: 'Key Project Company Information',
    data: [
      { key: 'Project company name', value: 'companyName', isAuthText: true },
      { key: 'Project company found date', value: 'pcFoundDate', isAuthTime: true },
      {
        key: 'Project company shareholders pay project capital',
        value: 'pcShareholdersPayProjectCapital',
        isAuthText: true,
      },
      { key: 'Project company shareholding structure', value: 'pcShareholdingStructure', isAuthText: true },
      { key: 'Performance assurance measures', value: 'performanceAssuranceMeasures', isAuthSingleFile: true }],
  },
  {
    title: 'Project Design and Construction',
    data: [
      { key: 'Project construction start date', value: 'constructionStartDate', isAuthTime: true },
      { key: 'Project construction completion date', value: 'constructionCompletionDate', isAuthTime: true },
      { key: 'Project construction progress', value: 'constructionProgress', isAuthText: true }],
  },
  {
    title: 'Project Operations',
    data: [
      { key: 'Project operation start date', value: 'operationStartDate', isAuthTime: true },
      {
        key: 'Actual expenditure of financial expenditure by government each year',
        value: 'govExpenditureEachYear',
        isAuthText: true,
      },
      { key: 'Project company performance monitoring report', value: 'pcPmr', isAuthMutiFile: true },
      { key: 'Mid-term evaluation report', value: 'mer', isAuthMutiFile: true },
      { key: 'Project company\'s financial report', value: 'pcFr', isAuthMutiFile: true },
      { key: 'PPP contract amendment agreement or supplementary agreement', value: 'pppSa', isAuthMutiFile: true },
      { key: 'Major changes or terminations of the project', value: 'majorChangesTerminations', isAuthText: true },
      {
        key: 'The situation of major breach of contract and performance guarantee, and the handling of public complaints',
        value: 'badEventHandling',
        isAuthText: true,
      },
      {
        key: 'Provisions, decisions, etc. that may be of significant impact on the project by the government',
        value: 'significantImpactOnGovernment',
        isAuthText: true,
      },
      {
        key: 'Major disputes, complaints of the project company of relevant parties',
        value: 'pcMajorDisputesComplaints',
        isAuthText: true,
      }],
  },
];

// 阶段4数据处理
const transfer: Array<any> = [{
  title: '',
  data: [
    {
      key: 'Composition of the transfer group, transfer procedures and criteria',
      value: 'transferGroupComposition',
      isAuthText: true,
    },
    { key: 'Lists of transfer assets or facilities or interests', value: 'transferList', isAuthSingleFile: true },
    { key: 'Transfer of assets or equity assessment report', value: 'assessmentReport', isAuthSingleFile: true },
    { key: 'Performance test plan', value: 'performanceTestPlan', isAuthSingleFile: true },
    {
      key: 'Removal of various types of guarantees or restrictions on the transfer of project assets or facilities',
      value: 'removalRestrictions',
      isAuthText: true,
    },
    { key: 'Project facility transfer compliance test results', value: 'testResult', isAuthSingleFile: true },
    { key: 'Project transfer completion date', value: 'completionTime', isAuthTime: true },
    { key: 'Project follow-up operation', value: 'followUpOperation', isAuthSingleFile: true },
    { key: 'Project warranty period', value: 'warrantyPeriod', isAuthTime: true }],
}];

const stageConfigs: Array<any> = [{ identification }, { procurement }, { implementation }, { transfer }];
const getStageInfo = ({ stageDatas, callBack }: any) => {
  const finalData = { identification: [], procurement: [], implementation: [], transfer: [] } as any;
  stageConfigs.forEach((config: any) => {
    Object.entries(config).forEach(([k, v]: any) => {
      v.forEach((stageTab: any) => {
        const result = stageTab.data.map((info: any) => toFormat({ ...info, data: stageDatas[k][info.value] }, callBack));
        finalData[k].push({ ...stageTab, data: result });
      });
    });
  });

  return finalData;
};

export { getUrlSearch, getStageInfo, getOrgId };
